#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("客户端");

    tcpSocket = new QTcpSocket(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_openBt_clicked()
{
    tcpSocket->connectToHost(ui->ipEdit->text(),ui->portEdit->text().toUInt());     //主动和该IP和端口对应的服务器相连
    connect(tcpSocket,SIGNAL(connected()),this,SLOT(connected_Slot()));  //如果和对方建立好连接，通信套接字会自动触发connected（）信号
}

void Widget::connected_Slot()
{
    QString temp = QString("Connect Server success！");
    ui->receiveEdit->appendPlainText(temp);
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));  //建立好连接之后，准备读取接收到的消息

}
void Widget::readyRead_Slot()
{
    ui->receiveEdit->appendPlainText(tcpSocket->readAll());  //将接受道德内容显示到窗口
}
void Widget::on_closeBt_clicked()
{
    tcpSocket->disconnect();
    tcpSocket->close();
}

void Widget::on_sendBt_clicked()
{
    tcpSocket->write(ui->sendEdit->text().toUtf8().data());
}
